//
//  DropDownViewController.m
//  leo
//
//  Created by 常艳 on 15/10/1.
//  Copyright (c) 2015年 mdx. All rights reserved.
//

#import "DropDownViewController.h"
#import "AddwatchTableViewCell.h"
#import "WatchTableViewCell.h"
#import "DataManager.h"
#import "ScanViewController.h"
#import "AppDelegate.h"
#import "SyncManager.h"
#import "MainPageViewController.h"
@interface DropDownViewController ()
@property(nonatomic,strong) DataManager *dataManager;
@property(nonatomic,strong) SyncManager *syncManager;
@property(nonatomic,assign) BOOL isRegisWatch;
@property(nonatomic,assign) BOOL isRegisAdd;
@property(nonatomic,strong) Watch *selectWatch;
@property(nonatomic,weak) AppDelegate *mydelegate;
@property(nonatomic,strong) UITableView *tableView;
@end

@implementation DropDownViewController
@synthesize tableArray;
@synthesize dataManager;
@synthesize syncManager;
@synthesize mydelegate;
@synthesize watchlist_bg;
-(void)dealloc
{
    [self removeObservers];
    self.dataManager=NULL;
    self.syncManager=NULL;
    self.selectWatch=NULL;
    self.mydelegate=NULL;
    self.tableView=NULL;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.extendedLayoutIncludesOpaqueBars=YES;
    [self registerObservers];
    dataManager=[[DataManager alloc] init];
    if(dataManager==NULL)
    {
        NSLog(@"%@,viewDidLoad,dataManager is null.",DATAMANAGER_TAG);
        return;
    }
    syncManager=[[SyncManager alloc] init];
    if(syncManager==NULL)
    {
        NSLog(@"%@,viewDidLoad,syncManager is null.",DATAMANAGER_TAG);
        return;
    }
    User *user=[User sharedSingleton];
    if(user==NULL)
    {
        NSLog(@"%@,viewDidLoad,user is null.",DATAMANAGER_TAG);
        return;
    }
    mydelegate=[[UIApplication sharedApplication] delegate];
    if(mydelegate==NULL)
    {
        NSLog(@"%@,viewDidLoad,mydelegate is null.",DATAMANAGER_TAG);
        return;
    }
    self.selectWatch=[dataManager getActiveWatch:user.uid];
    tableArray=[dataManager getWatchList:user.uid];
    self.isRegisAdd=NO;
    self.isRegisWatch=NO;
    float mainWidth=[UIScreen mainScreen].bounds.size.width;
    float fwidth=178*(mainWidth/375);
    float fheight=44;
    if(self.selectWatch!=NULL)
    {
        int maxRow=([UIScreen mainScreen].bounds.size.height-64-watchlist_bg.bounds.size.height)/44;
        if([tableArray count]+1>maxRow)
        {
            fheight=maxRow*44;
        }
        else
        {
            fheight=fheight+[tableArray count]*44;
        }

    }
    CGRect sf=CGRectMake(mainWidth/2-fwidth/2,64+watchlist_bg.bounds.size.height,fwidth,fheight);
    self.tableView=[[UITableView alloc] initWithFrame:sf];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.tableView.layer setMasksToBounds:YES];
    self.tableView.layer.cornerRadius=10;
    self.tableView.clipsToBounds=YES;
    self.tableView.userInteractionEnabled=YES;
    [self.view addSubview:self.tableView];
}
-(void)refreshData
{
    if(self.dataManager==NULL)
        return;
    User *user=[User sharedSingleton];
    if(user==NULL)
        return;
    self.selectWatch=[dataManager getActiveWatch:user.uid];
    tableArray=[dataManager getWatchList:user.uid];
    [self.tableView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if(self.view.window==nil)
    {
        self.view=nil;
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:YES];
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(tableArray!=NULL)
    {
        return [tableArray count]+1;
    }
    else
    {
        return 1;
    }
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = nil;
    NSInteger row=[indexPath row];
    if(row==[tableArray count])
    {
        cellIdentifier=@"addwatch";
        if(!self.isRegisAdd)
        {
            [tableView registerNib:[UINib nibWithNibName:@"AddwatchTableViewCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
            self.isRegisAdd=YES;
        }
        
        AddwatchTableViewCell *cell = (AddwatchTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        cell.backgroundColor=[UIColor clearColor];
        if(row==10)
        {
            cell.addImg.image=[UIImage imageNamed:@"manage_add@2x.png"];
        }
        return cell;
    }
    else
    {
        cellIdentifier=@"watch";
        if(!self.isRegisWatch)
        {
            [tableView registerNib:[UINib nibWithNibName:@"WatchTableViewCell" bundle:nil] forCellReuseIdentifier:cellIdentifier];
            self.isRegisWatch=YES;
        }
        
        WatchTableViewCell *cell = (WatchTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        cell.backgroundColor=[UIColor clearColor];
        Watch *watch=[tableArray objectAtIndex:row];
        if(watch!=NULL)
        {
            if(watch.pic_url!=NULL&&![watch.pic_url isEqualToString:@"(null)"])
            {
                cell.headImg.image=[UIImage imageNamed:[[Tooler getDocumentDirectory] stringByAppendingString:watch.pic_url]];
            }
            else
            {
                if(watch.gender==1)//女孩
                {
                    cell.headImg.image=[UIImage imageNamed:@"avater_girl.png"];
                }
                else
                {
                    cell.headImg.image=[UIImage imageNamed:@"avater_boy@2x.png"];
                }
                
            }
            if(watch.nickname!=NULL&&![watch.nickname isEqualToString:@"(null)"])
            {
                cell.nameLable.text=watch.nickname;
            }
            else
            {
                cell.nameLable.text=[NSString stringWithFormat:@"手表%d",(int)row+1];
            }
            if(watch.role==ADMIN)
            {
                cell.roleImg.image=[UIImage imageNamed:@"watchlist_key1@2x.png"];
            }
            else
            {
                cell.roleImg.image=[UIImage imageNamed:@"watchlist_key2@2x.png"];
            }
        }
        return cell;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.0f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row=[indexPath row];
    if(row<[tableArray count])
    {
        [(MainPageViewController *)self.motherNav dismiss];
        //更改本地数据库手表状态
        if(dataManager==NULL)
        {
            NSLog(@"%@,didSelectRowAtIndexPath,dataManager is null.",drop_tag);
            return;
        }
        Watch *watch=[tableArray objectAtIndex:row];
        if(watch==NULL||watch.deviceUid==NULL)
        {
            NSLog(@"%@,didSelectRowAtIndexPath,watch is null.",DATAMANAGER_TAG);
            return;
        }
        NSString *titleStr=NULL;
        if(watch.nickname!=NULL&&![watch.nickname isEqualToString:@"(null)"])
        {
            titleStr=watch.nickname;

        }
        else
        {
            titleStr=[NSString stringWithFormat:@"手表%d",(int)row+1];
        }
        [(MainPageViewController *)self.motherNav updateTitleLable:titleStr];        
        if(self.selectWatch!=NULL&&self.selectWatch.deviceUid!=NULL&&[watch.deviceUid intValue]==[self.selectWatch.deviceUid intValue])
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:SELECTWATCH object:nil  userInfo:nil];
        }
        if(self.selectWatch!=NULL&&self.selectWatch.deviceUid!=NULL&&[watch.deviceUid intValue]!=[self.selectWatch.deviceUid intValue])
        {
            self.selectWatch=watch;
            if(self.selectWatch.role==1)
                self.mydelegate.isAdmin=YES;
            else
                self.mydelegate.isAdmin=NO;
            
            dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
            if(queue==NULL)
            {
                NSLog(@"%@,getTaskPic,queue is null",DATAMANAGER_TAG);
                return;
            }
            dispatch_async(queue, ^{
                BOOL result=[dataManager updateWatchState:watch.deviceUid];
                if(result)
                {
                    //数据库状态更新成功，发送通知
                    [[NSNotificationCenter defaultCenter] postNotificationName:CHANGEWATCH object:nil  userInfo:nil];
                    NSLog(@"send notification:%@",CHANGEWATCH);
                }
                
            });


            
        }
        

    }
    else
    {
        if(row==10)
        {
            [LeoMsg showMsg:@"一个账号最大支持绑定10个手表，最多成为3个表的主管理员"];
            return;
        }
        self.mydelegate.addWatchMethod=1;
        ScanViewController *scanView=[[ScanViewController alloc] init];
        scanView.type=2;
        [(MainPageViewController *)self.motherNav dismiss];
        [self.motherNav.navigationController pushViewController:scanView animated:YES];
        
    }

    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    [(MainPageViewController *)self.motherNav dismiss];
}

-(void)registerObservers
{

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:CHANGEBABYINFO object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:UNBINDDEVICE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:BINDRELATIONCHANGE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:USERINFOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveNotification:) name:WATCHPHOTOUPDATE object:nil];
}
-(void)removeObservers
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:CHANGEBABYINFO object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UNBINDDEVICE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:BINDRELATIONCHANGE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:USERINFOUPDATE object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:WATCHPHOTOUPDATE object:nil];

}
- (void)receiveNotification:(NSNotification *)sender {
    if([sender.name isEqualToString:UNBINDDEVICE])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self refreshData];
            float mainWidth=[UIScreen mainScreen].bounds.size.width;
            float fwidth=178*(mainWidth/375);
            float fheight=44;
            if(self.selectWatch!=NULL)
            {
                fheight=fheight+[tableArray count]*44;
            }
            CGRect sf=CGRectMake(mainWidth/2-fwidth/2,64+watchlist_bg.bounds.size.height,fwidth,fheight);
            self.tableView.frame=sf;
            [self.tableView reloadData];
        });
    }
    else if([sender.name isEqualToString:CHANGEBABYINFO])
    {
        [self refreshData];
        [self.tableView reloadData];
    }
    else if([sender.name isEqualToString:BINDRELATIONCHANGE])
    {
        [self refreshData];
        float mainWidth=[UIScreen mainScreen].bounds.size.width;
        float fwidth=178*(mainWidth/375);
        float fheight=44;
        if(self.selectWatch!=NULL)
        {
            fheight=fheight+[tableArray count]*44;
        }
        CGRect sf=CGRectMake(mainWidth/2-fwidth/2,64+watchlist_bg.bounds.size.height,fwidth,fheight);
        self.tableView.frame=sf;
        [self.tableView reloadData];
    }
    else if([sender.name isEqualToString:USERINFOUPDATE])
    {
        [self refreshData];
        [self.tableView reloadData];
    }
    else if([sender.name isEqualToString:WATCHPHOTOUPDATE])
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self refreshData];
            [self.tableView reloadData];
        });

    }
   
}
@end
